﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Mvc;

namespace Common
{
    public class LoginAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var loginUser = filterContext.HttpContext.Session["LoginUser"];
            //When user has not login yet
            if (loginUser == null)
            {
                if (!filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    string js = "<script>alert('登陆超时，请重新登陆！');top.location.href='/Admin/Login/Login';</script>";
                    ContentResult content = new ContentResult();
                    content.Content = js;
                    filterContext.Result = content;
                }
                else
                {
                    filterContext.HttpContext.Response.AddHeader("SessionTimeout", "true");
                    filterContext.Result = new HttpStatusCodeResult(403, filterContext.HttpContext.Server.UrlEncode("登陆超时，请重新登陆"));
                }
                return;
            }
        }
    }
}
